import { request } from '@/api/request';
import { useAppSelector } from '@/redux/store';
import { useRequest } from 'ahooks';
import { useCallback, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { type YmColumnsType } from 'ym-design';
import { type ToolBarProps } from 'ym-design/es/YmTable/ToolBar';

export type QueryCustomField = {
  /**
   * @desc   人员id
   */
  personId: string;
  /**
   * @desc   企业id
   */
  entId: string;
  /**
   * @desc   查询类型
   */
  checkType: number;
  /**
   * @desc   所属路由
   */
  askType?: string;
};

export type CustomFieldsVO = QueryCustomField & {
  customFields: string;
};

export const queryCustomField = (data: QueryCustomField) => {
  return request<CustomFieldsVO>({ url: '/bill/api/order/queryCustomField', data });
};

export const addOrUpCustomField = (data: CustomFieldsVO) => {
  return request({ url: '/bill/api/order/addOrUpCustomField', data });
};

export type CacheColumnsOption<T> = {
  checkType: number;
  askType?: string;
  columns: YmColumnsType<T>;
};

type CacheColumnsResult<T> = {
  loading: boolean;
  handleColumns: YmColumnsType<T>;
  onColumnsChange: ToolBarProps['onColumnsChange'];
};

export default function useCacheColumns<T = any>(option: CacheColumnsOption<T>): CacheColumnsResult<T> {
  const { checkType, askType: PAskType, columns } = option;
  const location = useLocation();
  const entId = useAppSelector((state) => state.loginEnt.entId);
  const personId = useAppSelector((state) => state.loginUser.personId);
  const [showColumns, setColumns] = useState(columns);

  const askType = PAskType ?? location.pathname.split('/').at(-1);

  const { loading } = useRequest(
    async () => {
      const { data } = await queryCustomField({
        entId,
        personId,
        askType,
        checkType,
      });

      return data;
    },
    {
      ready: Boolean(askType) && Boolean(checkType),
      refreshDeps: [askType, checkType],
      onSuccess(data) {
        const cacheColumns = data?.customFields ? JSON.parse(data.customFields) : [];
        if (cacheColumns.length) {
          const newColumns = cacheColumns.map((column: YmColumnsType<T>[number]) => {
            const localColumn = columns.find((c) => c.key === column.key);
            return {
              ...localColumn,
              hidden: column.hidden,
              fixed: column.fixed,
            };
          });
          const lastColumn = columns.at(-1);
          if (lastColumn?.key === '_operate') newColumns.push(lastColumn);
          setColumns(newColumns);
        }
      },
    },
  );

  const onColumnsChange = useCallback(
    (newColumns: YmColumnsType<T>, type: any) => {
      if (type.type !== 'reset') {
        setColumns(newColumns);
      } else {
        setColumns(columns);
      }
      const customFields = newColumns.filter((c) => c.title !== '操作' || c.key !== '_operate');
      const params = {
        personId,
        entId,
        checkType,
        askType,
        customFields: JSON.stringify(customFields),
      };
      return addOrUpCustomField(params);
    },
    [personId, entId, checkType, askType],
  );

  return {
    loading,
    handleColumns: showColumns,
    onColumnsChange,
  };
}
